﻿// ***********************************************************************
// Assembly         : ElFinder.Net
// Author           : Lolo
// Created          : 06-05-2013
//
// Last Modified By : Lolo
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="JsonDataContractResult.cs" company="">
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace System.Web.Mvc
{
    /// <summary>
    /// Class JsonDataContractResult
    /// </summary>
    internal class JsonDataContractResult : JsonResult
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonDataContractResult" /> class.
        /// </summary>
        /// <param name="data">The data.</param>
        public JsonDataContractResult(object data)
        {
            Data = data;
        }
        /// <summary>
        /// Permet le traitement du résultat d'une méthode d'action par un type personnalisé qui hérite de la classe <see cref="T:System.Web.Mvc.ActionResult" />.
        /// </summary>
        /// <param name="context">Contexte dans lequel le résultat est exécuté.</param>
        /// <exception cref="System.ArgumentNullException">context</exception>
        /// <exception cref="System.InvalidOperationException">Get is not allowed</exception>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Get is not allowed");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(response.Output, Data);
            }
        }
    }
}